package com.example.nettyim.handler;

import com.example.nettyim.message.ChatRequestMessage;
import com.example.nettyim.message.ChatResponseMessage;
import com.example.nettyim.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * author :sherlock.lin
 * date : Created in 2023/2/13
 * description :
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage chatRequestMessage) throws Exception {
        String to = chatRequestMessage.getTo();
        Channel channel = SessionFactory.getSession().getChannel(to);
        //在线
        if (channel != null) {
            channel.writeAndFlush(new ChatResponseMessage(chatRequestMessage.toString(), chatRequestMessage.getContent()));
        } else {
            channelHandlerContext.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或者不在线"));
        }
    }
}
